<template>
  <a-layout>
    <a-layout-content style="background: #fff;">
      <a-page-header>
        <template slot="title">
          角色菜单
        </template>
        <template #extra>
          <a-button-group>
            <a-button @click="BuildAllCache">
              刷新缓存
            </a-button>
            <a-button @click="exportData">
              下载
            </a-button>
            <a-upload
              name="file"
              :show-upload-list="false"
              :multiple="false"
              :action="importUrl + '?token=' + $token.getRefreshToken()"
              @change="handleChangeFile"
            >
              <a-button> <a-icon type="upload" />导入 </a-button>
            </a-upload>
          </a-button-group>
        </template>
      </a-page-header>

      <a-tabs
        v-model="platKey"
        style="margin: 0 16px; background-color: #fff;"
        type="card"
        @change="queryForm"
      >
        <a-tab-pane
          v-for="(item, index) in platTreeData"
          :key="index"
          :tab="item.area_name"
        />
        <div slot="tabBarExtraContent" v-has="'systemAreaType.children'">
          <a-tooltip style="margin-right: 6px;">
            <template slot="title">
              刷新
            </template>
            <a-icon type="reload" @click="querySystemAreaForce()" />
          </a-tooltip>
          <a-tooltip style="margin-right: 6px;">
            <template slot="title">
              设置子类
            </template>
            <a-icon
              type="setting"
              class="link"
              @click="
                systemAreaId = $e.platform
                systemAreaVisible = true
              "
            />
          </a-tooltip>
        </div>
      </a-tabs>

      <a-layout style="margin: 0 16px;">
        <a-layout-sider
          style="background: #fff; position: relative;"
          :width="160"
        >
          <div
            v-has="'systemAreaType.children'"
            style="position: absolute; right: 8px; top: 13px; z-index: 100;"
          >
            <a-tooltip style="margin-right: 6px;">
              <template slot="title">
                刷新
              </template>
              <a-icon type="reload" @click="querySystemAreaForce()" />
            </a-tooltip>
            <a-tooltip style="margin-right: 6px;">
              <template slot="title">
                设置子类
              </template>
              <a-icon
                type="setting"
                class="link"
                @click="
                  systemAreaId = $e.role
                  systemAreaVisible = true
                "
              />
            </a-tooltip>
          </div>
          <a-menu v-model="roleKey" theme="light" mode="inline">
            <template v-for="(item, index) in roleTreeData">
              <a-sub-menu
                v-if="item.children && item.children.length > 0"
                :key="index"
              >
                <span slot="title">
                  <app-icon :type="item.ico_str" />
                  <span>
                    {{ item.area_name }}
                  </span>
                </span>
                <a-menu-item
                  v-for="itemSec in item.children"
                  :key="itemSec.key"
                >
                  <router-link :to="{ path: itemSec.link }">
                    <span>{{ itemSec.area_name }}</span>
                  </router-link>
                </a-menu-item>
              </a-sub-menu>

              <a-menu-item v-else :key="index">
                <router-link :to="{ path: item.link }">
                  <span>
                    {{ item.area_name }}
                  </span>
                </router-link>
              </a-menu-item>
            </template>
          </a-menu>
        </a-layout-sider>
        <a-layout-content style="background: #fff;">
          <div style="margin: 10px;">
            <a-button @click="editVisible = true">
              修改菜单
            </a-button>

            <a-tree
              v-if="data && data.length > 0"
              :tree-data="data"
              show-icon
              show-line
              default-expand-all
              :replace-fields="{
                title: 'title',
                key: 'id',
              }"
            >
              <app-icon slot="icon" slot-scope="item" :value="item.icon" />

              <span
                slot="title"
                slot-scope="item"
                :style="
                  item.status != 1
                    ? {
                        color: '#999',
                      }
                    : {}
                "
                style="position: relative;"
              >
                {{ item.title }}
                <span style="color: #999; margin-left: 10px;">
                  <span v-if="item.page_type == 0">目录</span>
                  <span v-else-if="item.page_type == 1">
                    菜单 {{ item.link_mark }} {{ item.page_url_show }}
                  </span>
                  <span v-else-if="item.page_type == 2">
                    按钮 {{ item.page_mark }} {{ item.link_url_show }}
                  </span>
                </span>
              </span>
            </a-tree>
            <a-empty v-else />
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout-content>

    <edit
      v-model="editVisible"
      :plat-code="plat_code"
      :role-code="role_code"
      :select-items="dataSelect"
      @change="fetch()"
    />

    <systemAreaList :id="systemAreaId" v-model="systemAreaVisible" />
  </a-layout>
</template>
<script>
import userRoleMenu from "@/api/userRoleMenu"
import systemAreaType from "@/api/systemAreaType"
import FileSaver from "file-saver"

export default {
  components: {
    edit: () => import("./edit"),
    systemAreaList: () => import("../systemArea/list"),
  },
  data() {
    return {
      //平台管理
      platTreeData: [],
      platKey: 0,

      roleTreeData: [],
      roleKey: [0],

      systemAreaId: undefined,
      systemAreaVisible: false,

      //
      editVisible: false,
      plat_code: undefined,
      role_code: undefined,

      data: [],
      dataSelect: [],

      importUrl: this.$http.PrefixURL + userRoleMenu.prefixUrl,
    }
  },
  watch: {
    roleKey() {
      this.querySystemArea()
    },
  },
  mounted() {
    this.$emit("menu", "/home/userRoleMenu/list")
    this.querySystemArea()
  },
  methods: {
    querySystemAreaForce() {
      systemAreaType.cacheClean(this.$e.platform)
      systemAreaType.cacheClean(this.$e.role)
      this.querySystemArea()
    },
    querySystemArea() {
      this.platTreeData = []
      systemAreaType.cache(this.$e.platform).then((response) => {
        if (response.code !== 1) {
          this.$message.warning(response.message)
          return
        }
        if (response.data) {
          this.platTreeData = response.data.data_menu
          if (this.platTreeData.length > 0) {
            this.queryForm()
          }
        }
      })
      systemAreaType.cache(this.$e.role).then((response) => {
        if (response.code !== 1) {
          this.$message.warning(response.message)
          return
        }
        if (response.data) {
          this.roleTreeData = response.data.data_menu
          if (this.roleTreeData.length > 0) {
            this.queryForm()
          }
        }
      })
    },
    queryForm() {
      this.fetch()
    },
    async fetch() {
      if (
        !this.platTreeData ||
        this.platTreeData.length <= 0 ||
        !this.platTreeData[this.platKey] ||
        !this.roleTreeData ||
        this.roleTreeData.length <= 0 ||
        !this.roleTreeData[this.roleKey[0]]
      )
        return

      this.plat_code = this.platTreeData[this.platKey].area_code
      this.role_code = this.roleTreeData[this.roleKey[0]].area_code

      if (!this.plat_code || !this.role_code) return

      this.data = []
      this.dataSelect = []
      this.loading = true
      await userRoleMenu
        .query(this.$e.platform, this.plat_code, this.$e.role, this.role_code)
        .then((response) => {
          if (response.code !== 1) {
            this.$message.warning(response.message)
            return
          }
          if (!response.data) return
          this.data = response.data.tree

          if (response.data.arr) {
            response.data.arr.forEach((element) => {
              this.dataSelect.push(element.page_role_id)
            })
          }
          return
        })
        .catch((e) => {
          console.log(e)
        })
      this.loading = false
    },
    BuildAllCache() {
      userRoleMenu
        .cacheClean()
        .then((response) => {
          if (response.code !== 1) {
            this.$message.warning(response.message)
            return
          }
          this.$message.success(response.message)
          return
        })
        .catch((e) => {
          console.log(e)
        })
    },
    exportData() {
      userRoleMenu.export().then((response) => {
        if (response.code !== 1) {
          this.$message.warning(response.message)
          return
        }

        const data = JSON.stringify(response.data, true, 4)
        const blob = new Blob([data], { type: "" })
        FileSaver.saveAs(blob, "menu.json")
      })
    },
    handleChangeFile(info) {
      const status = info.file.status
      if (status === "done") {
        const response = info.file.response
        if (response.code !== 1) {
          this.$message.error(
            `上传文件 ${info.file.name} 失败, ${response.message}`
          )
          return
        }
        this.$message.success(response.message)
        this.fetch()
      }
      if (status === "error") {
        const response = info.file.response
        this.$message.error(
          `上传文件 ${info.file.name} 失败, ${response.message}`
        )
        return
      }
    },
  },
}
</script>

<style lang="less" type="text/less" scoped>
.ant-form-item {
  margin-bottom: 6px;
}

.changeGhost li {
  list-style: none;
  padding: 6px;
}
.changeGhost li:nth-child(2n-1) {
  background: #f8f8f8;
}
.ghost {
  opacity: 0.5;
  background: #c8ebfb !important;
}
.changeDiv {
  cursor: pointer;
}
.hide_action {
  display: none;
  padding-left: 10px;
  .action {
    padding-left: 4px;
  }
}
</style>
